package com.framework.modules.base.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.common.utils.PageUtils;
import com.framework.common.utils.Query;

import com.framework.modules.base.dao.UserBalanceDao;
import com.framework.modules.base.entity.UserBalanceEntity;
import com.framework.modules.base.service.UserBalanceService;
import org.springframework.transaction.annotation.Transactional;


@Service("userBalanceService")
public class UserBalanceServiceImpl extends ServiceImpl<UserBalanceDao, UserBalanceEntity> implements UserBalanceService {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<UserBalanceEntity> page = this.selectPage(
                new Query<UserBalanceEntity>(params).getPage(),
                new EntityWrapper<UserBalanceEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public Object updateBalance(Integer uid, BigDecimal amount, String type) {
        UserBalanceEntity entity = this.baseMapper.selectById(uid);
        BigDecimal balance = entity.getBalance();
        BigDecimal totalAmount = entity.getTotalAmount();
        String result = "";
        if (entity == null) {
            return 0;
        }
        switch (type) {
            case "add":
                balance = balance.add(amount);
                entity.setBalance(balance);
                break;
            case "reduce":
                if (balance.compareTo(amount) == -1) {
                    result = "余额不足";
                } else {
                    balance = balance.subtract(amount);
                    entity.setBalance(balance);
                    entity.setTotalAmount(totalAmount.add(amount));
                }
                break;
            default:
                result = "余额更新参数有误";

        }
        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        if (this.baseMapper.updateById(entity) == 0) {
            return "余额更新失败";
        }
        return balance;
    }

    @Override
    public Integer addCoin(Integer uid, Integer coin) {
        return this.baseMapper.addCoin(uid,coin);
    }

}
